<script lang="ts" setup>
  import type { FormInstance } from 'element-plus'
  import request from '@/utils/request'
  import { baseURL } from '@/config'
  import { useUserStore } from '@/store/modules/user'
  import FileUpload from '@/components/common/FileUpload'

  const props = defineProps({
    renderOptions: {
      required: true,
      type: Array,
      default: () => [],
    },
    renderData: {
      required: true,
      type: Object,
    },
    requestUrl: {
      // 业务场景请求地址
      required: true,
      type: Boolean,
    },
    moduleCode: {
      // 业务场景编码
      required: true,
      type: Boolean,
    },
    rules: {
      type: Object,
      default: () => {},
    },
  })
  const emits = defineEmits(['fetch-data'])
  const userStore = useUserStore()
  const $baseMessage = inject('$baseMessage')
  const { token } = storeToRefs(userStore)
  const dialogFormRef = ref<FormInstance>()
  const fileUploadRef = ref(null)
  const visible = ref(false)
  const upload = reactive({
    url: `${baseURL}/zgyp-system/api/v1/files`,
    headers: {},
  })
  const title = ref('')
  const state = reactive({
    form: {
      count: 1,
    },
  })

  const showEdit = (row) => {
    if (!row) {
      title.value = '新增'
    } else {
      title.value = '编辑'
      state.form = JSON.parse(JSON.stringify(row))
    }
    visible.value = true
  }

  const requestAdd = (data: any = {}) => {
    return request({
      url: `${props.requestUrl}/add`,
      method: 'post',
      data,
    })
  }

  const requestUpdate = (data: any = {}) => {
    return request({
      url: `${props.requestUrl}/modify`,
      method: 'put',
      data,
    })
  }

  const close = () => {
    dialogFormRef.value.resetFields()
    if (fileUploadRef.value[0] && fileUploadRef.value[0].uploadRef) {
      fileUploadRef.value[0].uploadRef.clearFiles()
    }
    state.form = {
      count: 1,
    }
    visible.value = false
  }

  const save = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid) => {
      if (valid) {
        try {
          const params = {
            typeCode: props.moduleCode,
            form: JSON.parse(JSON.stringify(state.form)),
          }
          const { msg } =
            title.value === '新增'
              ? await requestAdd(params)
              : await requestUpdate(params)
          $baseMessage(msg, 'success', 'vab-hey-message-success')
          emits('fetch-data')
          close()
        } catch (err) {
          console.error(err)
        }
      }
    })
  }

  onMounted(() => {
    const tokens = JSON.parse(JSON.stringify(token))
    upload.headers['Authorization'] = `Bearer ${tokens._object.token}`
  })

  defineExpose({
    showEdit,
  })
</script>

<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="600"
    :before-close="close"
    :close-on-click-modal="false"
  >
    <el-form
      ref="dialogFormRef"
      :model="state.form"
      :rules="rules"
      label-width="100px"
      @submit.prevent
    >
      <template v-for="item in renderOptions" :key="item.fieldProperty">
        <el-form-item
          v-if="item.onFormCol === 1"
          :label="item.displayName"
          :required="item.formValidation ? true : false"
          :prop="item.fieldProperty"
          :rules="
            item.formValidation
              ? {
                  required: true,
                  message: '必填项不能为空',
                  trigger: ['blur', 'change'],
                }
              : ''
          "
        >
          <el-input
            v-if="item.formType === 10"
            v-model="state.form[item.fieldProperty]"
            clearable
            placeholder="请输入"
          />
          <el-input
            v-if="item.formType === 11"
            v-model="state.form[item.fieldProperty]"
            type="textarea"
            clearable
            :autosize="{ minRows: 2 }"
            placeholder="请输入"
          />
          <el-input-number
            v-if="item.formType === 12 && item.fieldType === 2"
            v-model="state.form[item.fieldProperty]"
            placeholder="请输入"
          />
          <el-input-number
            v-if="item.formType === 12 && item.fieldType === 3"
            v-model="state.form[item.fieldProperty]"
            :precision="2"
            :controls="false"
            placeholder="请输入"
          />
          <file-upload
            v-if="item.formType === 30"
            ref="fileUploadRef"
            v-model="state.form[item.fieldProperty]"
            show-file-list
          />
          <el-select
            v-if="item.formType === 40"
            v-model="state.form[item.fieldProperty]"
            clearable
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="option in renderData[item.fieldProperty].data"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
          <el-tree-select
            v-if="item.formType === 42"
            ref="treeSelectRef"
            v-model="state.form[item.fieldProperty]"
            check-strictly
            filterable
            :data="renderData[item.fieldProperty].data"
            :render-after-expand="false"
          />
          <el-date-picker
            v-if="item.formType === 20"
            v-model="state.form[item.fieldProperty]"
            type="date"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择"
          />
        </el-form-item>
      </template>
      <el-form-item
        v-if="title == '新增'"
        label="数量"
        prop="count"
        required
        :rules="{
          required: true,
          message: '必填项不能为空',
          trigger: ['blur', 'change'],
        }"
      >
        <el-input-number v-model="state.form.count" :min="1" />
        <span style="font-size: 12px; margin-left: 10px">
          (默认添加1/件 资产,可输入数量批量添加)
        </span>
      </el-form-item>
    </el-form>

    <template #footer>
      <span>
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="save(dialogFormRef)">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
